package com.bby.disk.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpStatus;
import com.bby.common.config.GlobalSettings;
import com.bby.common.exception.BBYException;
import com.bby.common.model.Permission;
import com.bby.common.model.PermissionDetail;
import com.bby.common.model.PmMessage;
import com.bby.common.model.PmMessageDeal;
import com.bby.common.utils.R;
import com.bby.disk.manager.virtual.VirtualManager;
import com.bby.disk.manager.virtual.VirtualObject;
import com.bby.disk.util.BBYFileSystem;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

/**
 * 网盘-微服务之间通信
 */
@RestController
@RequestMapping("admin")
public class DiskEurekaApi {

    /**
     * 新建用户
     * @param userId 用户id
     * @param verification api密码
     * @return
     */
    @RequestMapping("register")
    public R register(String userId, String verification){
        if (GlobalSettings.REGISTER_VERIFICATION.equals(verification)){
            try {
                File avatar = BBYFileSystem.get(userId);
                File dir = new File(GlobalSettings.ROOT_PATH+File.separator+"settings","defaultAvatar");
                File[] files = dir.listFiles();
                if (files!=null && files.length>0){
                    int index = ((int) (Math.random()*10000))%(files.length-1);
                    FileUtil.copy(files[index], avatar,true);
                }
            }catch (Exception e){
                return R.error(e.getMessage());
            }
        }
        return R.error(HttpStatus.HTTP_NOT_AUTHORITATIVE,"密码错误！");
    }

    /**
     * 处理权限请求
     * @param message 要处理的message
     * @return
     */
    @RequestMapping("dealPmMessage")
    public Boolean dealPmMessage(@RequestBody PmMessage message){
        PmMessageDeal deal = message.getDeal();
        PermissionDetail detail = deal.getAgree();
        int flag;
        if ("user".equals(deal.getType())){
            flag = 0;
        }else {
            flag = "ann".equals(deal.getType())? 1:2;
        }
        List<VirtualObject> list = VirtualManager.findFiles(message.getFileIds());
        for (VirtualObject file : list) {
            Permission permission = file.getPermission();
            permission.setOpen(true);
            if (flag == 0){
                permission.setUser(detail);
            }else if (flag == 1){
                permission.setAnn(detail);
            }else {
                permission.setCustom(detail);
                permission.setCustomGroup(deal.getCustomGroup());
            }
            try {
                VirtualManager.editPermission(file,permission);
            } catch (BBYException ignored) {}
        }
        return true;
    }

}
